<?php
namespace AuctionCore\Common;

/**
 * redis操作类
 *
 * @author爱民
 */
class PhpRedis
{
    private $redis = null;

    public function __construct($dbIndex = false)
    {
        $redis = new \Redis();
        if ($this->redis == null) {
            $redis->connect(C('REDIS_HOST'), C('REDIS_PORT'), 1);
            $this->redis = $redis;
        }
        if ($dbIndex !== false) {
            $this->select($dbIndex);
        } else {
            $this->select(1);
        }
    }

    public function ping()
    {
        return $this->redis->ping();
    }

    public function select($num)
    {
        return $this->redis->select($num);
    }

    public function set($key, $vale, $expire = false)
    {

        $this->redis->set($key, $vale);

        if ($expire) {
            $this->redis->expire($key, $expire);
        }

    }

    public function get($key)
    {
        return $this->redis->get($key);
    }

    public function del($key)
    {
        return $this->redis->delete($key);
    }

    public function getRedis()
    {
        return $this->redis;
    }

    public function lock($key)
    {
        return $this->redis->setNx($key, 1) ? true : false;
    }

    public function lock_wait($key)
    {
        $r = $this->lock($key);
        if (!$r) {
            for ($i = 0; $i < 5; $i++) {
                usleep(rand(500, 1000));
                $r = $this->lock($key);
                if ($r)
                    break;
                $i++;
            }
        }
        return $r;
    }

    public function unlock($key)
    {
        $this->redis->delete($key);
    }

    public function incr($key)
    {
        $this->redis->incr($key);
    }

    public function lPush($key, $value)
    {
        return $this->redis->lPush($key, $value);
    }

    public function rPush($key, $value)
    {
        return $this->redis->rPush($key, $value);
    }
}